package com.jiazhong.spring.ioc.mybatis.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

import javax.sql.DataSource;

@Configuration
@MapperScan("com.jiazhong.spring.ioc.mybatis.mapper")
public class MyBatisConfig {

    @Bean(value = "dataSource")
    public DataSource getDataSource() {
        // 产生了数据源
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUsername("root");
        dataSource.setPassword("a123456");
        dataSource.setUrl("jdbc:mysql://localhost:3306/test");
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        return dataSource;
    }

    @Bean
    public SqlSessionFactoryBean getSqlSessionFactory(DataSource dataSource) {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        // 加载数据源
        sqlSessionFactoryBean.setDataSource(dataSource);
        // 加载config.xml
        sqlSessionFactoryBean.setConfigLocation(new ClassPathResource("config.xml"));
        return sqlSessionFactoryBean;
    }
}
